package com.ruoyi.web.controller.system;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.utils.RSAUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.redis.RedisUtil;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.framework.jwt.utils.JwtUtils;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@Slf4j
@RestController()
@RequestMapping("/jwt")
public class SysJwtLoginController extends BaseController
{

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private ISysUserService userService;

    @Resource
    private SysPasswordService passwordService;

    /**
     * 获取session公钥
     *
     * @return
     */
    @GetMapping("/getRequestId")
    public AjaxResult getRequestId() {
        String requestId = UUID.randomUUID().toString();
        Map<String, String> result = new HashMap<>();
        result.put("requestId", requestId);
        Map<String, String> keyMaps = null;
        try {
            keyMaps = RSAUtil.genKeyPairNodeRsa(512);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(keyMaps != null){
            // 记录私钥
            redisUtil.set(requestId, keyMaps.get("private"),300);
            result.put("publicKey", keyMaps.get("public"));
        }
        return AjaxResult.success(result);
    }

    @PostMapping("/userLogin")
    public AjaxResult jwtLogin(@RequestBody Map<String, String> params) {
        if (!params.containsKey("requestId")) {
            return AjaxResult.error("requestId是必填参数");
        }

        if (!params.containsKey("playload")) {
            return AjaxResult.error("playload是必填参数");
        }
        String requestId = params.get("requestId");
        if(StringUtils.isNull(redisUtil.get(requestId))){
            return AjaxResult.error("无效的requestId");
        }

        Map<String, String> json = null;
        try {
            String privateKey = (String)redisUtil.get(requestId);
            String playload = params.get("playload");
            String text = RSAUtil.decryptNodeRsa(playload, privateKey);
            ObjectMapper mapper = new ObjectMapper();
            json = mapper.readValue(text, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (json == null) {
            return AjaxResult.error("非法请求");
        }
        String username = json.get("username");
        String password = json.get("password");

        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            return AjaxResult.error("账号和密码不能为空!");
        }

        SysUser user = userService.selectUserByLoginName(username);
        if (user == null)
        {
            return AjaxResult.error("用户不存在/密码错误!");
        }

        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            return AjaxResult.error("对不起，您的账号已被删除!");
        }

        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            return AjaxResult.error("用户已封禁，请联系管理员!");
        }

        if (!passwordService.matches(user, password))
        {
            return AjaxResult.error("用户不存在/密码错误!");
        }

        String token = JwtUtils.createToken(username, user.getPassword());
        return AjaxResult.success("登录成功").put("token", token);
    }

}
